/**
 * Created by senlin.gu on 18/08/07
 * Functionprofile主页面
 */
import React from 'react'
import {connect} from 'react-redux'
import 'styles/setting/function-profile/function-profile.scss'
import {Button, Checkbox, Col, Input, message, Radio, Row, Spin, Alert} from 'antd'
import FunctionProfileService from 'containers/setting/function-profile/function-profile.service.js';
import FunctionProfileHandler from 'containers/setting/function-profile/function-profile.handler.js';
import {messages, deepFullCopy} from "share/common";

const RadioGroup = Radio.Group;

class FunctionProfile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      mode: '',
      userMode: '',
      //渲染界面用的FunctionProfile
      functionProfileList: [],
      functionProfileTabs: [],
      //系统返回的FunctionProfile
      systemProfileMap: {},
      loading: true,
      saving: false,
      currentMode: '',
      currentSelectTab: 'Display',
      inputText: '',
      defaultBoolean: {
        "yes": true,
        "no": false
      }
    }
  }

  componentWillMount() {
    //console.log('componentWillMount...');
    this.queryFunctionProfile();
  }

  //查询FunctionProfile
  queryFunctionProfile() {
    //console.log('this.props.tenantMode ' + JSON.stringify(this.props.tenantMode));
    //console.log('this.props.company ' + JSON.stringify(this.props.company));

    this.setState(
      {
        loading: true
      });

    let userMode = 'group';
    let mode = '租户模式';
    if (!this.props.tenantMode) {
      userMode = 'company';
      mode = '公司模式-' + this.props.company.name;
    }

    this.setState({
      mode: mode,
      userMode: userMode
    });

    let systemProfile;
    let baseProfileTable = FunctionProfileHandler.getBaseProfileTable(userMode);

    FunctionProfileService.getPersonalFunctionProfile(userMode).then((res) => {
      if (res.status == 200) {
        //console.log('FunctionProfileService.getPersonalFunctionProfile res ' + JSON.stringify(res));
        if (res.status == 200) {
          if (userMode == 'company') {
            systemProfile = res.data.profileDetail;
          } else {
            systemProfile = res.data;
          }

          this.setState(
            {
              systemProfileMap: systemProfile
            });

          let screenProfile = FunctionProfileHandler.analysisProfile(systemProfile, baseProfileTable);
          this.setState(
            {
              functionProfileList: screenProfile
            });

          //console.log('this.state.functionProfileList ' + JSON.stringify(this.state.functionProfileList))
        }
        this.setState(
          {
            loading: false
          });
      }
    }, (err) => {
    });
    this.setState({
      functionProfileTabs: deepFullCopy(FunctionProfileHandler.getFunctionProfileTabs())
    });
  }

  //保存FunctionProfile
  saveFunctionProfile() {
    this.setState({
      'saving': true
    });

    let processedProfile = {};
    let userMode = this.state.userMode;
    let functionProfileList = this.state.functionProfileList;
    let systemProfileMap = this.state.systemProfileMap;
    let companyProfile = this.props.company;

    //console.log('saveFunctionProfile... ');
    //console.log('saveFunctionProfile functionProfileList ' + JSON.stringify(functionProfileList));
    //console.log('saveFunctionProfile userMode ' + userMode);
    //console.log('saveFunctionProfile companyProfile ' + JSON.stringify(companyProfile))

    if (userMode === 'company') {
      processedProfile.entityOID = companyProfile.companyOID;
      processedProfile.companyOID = null;
      processedProfile.entityType = 1003;
      processedProfile.tenantId = null;
    } else if (userMode === 'group') {
      processedProfile.entityOID = null;
      processedProfile.companyOID = null;
      processedProfile.entityType = '2003';
    } else {
      this.setState({
        'saving': false
      });
      return;
    }

    //console.log('systemProfileMap ' + JSON.stringify(systemProfileMap));
    //console.log('functionProfileList ' + JSON.stringify(functionProfileList));

    let result = FunctionProfileHandler.processSubmitProfile(systemProfileMap, functionProfileList);

    //console.log('FunctionProfileHandler.processSubmitProfile result ' + JSON.stringify(result));

    if (result.status == 'S') {
      processedProfile.profileDetail = result.profileDetail;
      //console.log('saveFunctionProfile processedProfile ' + JSON.stringify(processedProfile));
      FunctionProfileService.savePersonalFunctionProfile(processedProfile, userMode).then((res) => {
        message.success('保存配置文件成功！');
        this.setState({
          'saving': false
        });
        this.queryFunctionProfile()
      }, err => {
        this.setState({
          'saving': false
        });
        message.success('保存配置文件失败，请修改后重新保存！');
        console.log('FunctionProfileService.savePersonalFunctionProfile err ' + JSON.stringify(err))
      });
    } else {
      console.log('result.errorMsg ' + result.errorMsg);
      message.error(result.errorMsg);
      this.setState({
        'saving': false
      });
    }

  }

  //选择Function Profile 标签
  selectProfileTab(tab) {
    //console.log('selectProfileTab...');
    var tabs = this.state.functionProfileTabs;
    tabs.forEach((tab1) => {
      if (tab1.code == tab.code) {
        tab1.selected = true;
      } else {
        tab1.selected = false;
      }
    });
    this.setState({
      functionProfileTabs: tabs,
      currentSelectTab: tab.code
    });
  }

  radioGroupChange = (profile) => {
    //console.log('radio checked profile ', JSON.stringify(profile));
    return (e) => {
      //console.log('radio checked', e.target.value);
      profile.value = e.target.value;

      //console.log('radioGroupChange profile ' + JSON.stringify(profile));
      //console.log('radioGroupChange this.state.functionProfileList ' + JSON.stringify(this.state.functionProfileList));

      this.setState({'functionProfileList': this.state.functionProfileList});
    }
  };

  handleTextChange = (profile) => {
    //console.log('handleInputChange ', JSON.stringify(profile));
    return (e) => {
      //console.log('handleInputChange profile ', JSON.stringify(profile));
      //console.log('handleInputChange e.target.value ', e.target.value);
      profile.value = e.target.value;
      this.setState({'functionProfileList': this.state.functionProfileList});
    }
  };

  checkboxChange = (profile) => {
    //console.log('handleInputChange ', JSON.stringify(profile));
    return (e) => {
      //console.log('checkboxChange ', e.target.checked);
      profile.enabledFlag = e.target.checked;
      setTimeout(() => {
        this.setState({'functionProfileList': this.state.functionProfileList});
      }, 0)
    }
  };

  filterInputChange = (e) => {
    //console.log('handleInputChange ', e.target.value);
    this.setState({'inputText': e.target.value});
  };

  filterProfile(code, description) {
    if (this.state.inputText && this.state.inputText !== '') {
      if (code.indexOf(this.state.inputText) > -1 || description.indexOf(this.state.inputText) > -1) {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  }

  renderOwner(profile) {
    if (profile.owner == 'all') {
      return (
        <secter>
          <span className="active-type">app</span>
          <span className="active-type">web</span>
        </secter>
      )
    } else if (profile.owner) {
      return (
        <span className="active-type">{profile.owner}</span>
      )
    } else {
      return (<span></span>)
    }
  }

  renderProfileValue(profile) {
    if (profile.category == 'closed' && !profile.enabledFlag) {
      return (
        <label>
          <Checkbox checked={profile.enabledFlag}
                    onChange={this.checkboxChange(profile)}/>
          <span style={{'marginLeft': '5px'}}>
            添加此项配置
          </span>
        </label>
      );
    }
    if (profile.componentType === 'boolean') {
      return (
        <RadioGroup onChange={this.radioGroupChange(profile)}
                    value={profile.value}>
          <Radio value={this.state.defaultBoolean.yes}>
            {profile.active}
          </Radio>
          <Radio value={this.state.defaultBoolean.no}>
            {profile.inactive}
          </Radio>
        </RadioGroup>
      );
    } else if (profile.componentType === 'radio') {
      return (
        <RadioGroup onChange={this.radioGroupChange(profile)}
                    value={profile.value}>
          {profile.lovList.map((lov) => (
            <Radio key={lov.value}
                   value={lov.value}>{lov.title}</Radio>
          ))}
        </RadioGroup>
      );
    } else if (profile.componentType === 'number') {
      return (
        <Input type="number"
               value={profile.value}
               onChange={this.handleTextChange(profile)}/>
      );
    } else if (profile.componentType === 'string' || profile.componentType === 'object') {
      if(profile.readOnly){
        return (
          <label>
            <span style={{'marginLeft': '5px'}}>
              {profile.value}
            </span>
          </label>
        )
      }else{
        return (
          <Input type="textarea"
                 value={profile.value}
                 onChange={this.handleTextChange(profile)}/>
        );
      }
    }
  }

  render() {
    const {
      functionProfileTabs,
      functionProfileList,
      loading,
      currentSelectTab
    } = this.state;
    return (
      <div className="function-profile">
        <Alert
          message={messages('setting.key1646')/*配置文件优先级*/}
          description={messages('setting.key1647')/*公司配置高于租户配置，即：相同配置项以公司配置为准；若公司的配置项与租户一致，对应公司无需重新配置。*/}
          type="info"
          showIcon
        />
        <Row className="profile-category">
          {functionProfileTabs.map((tab) => (
            <Col key={tab.code} span={1}
                 className={`category-name ${ tab.selected && tab.selected ? 'selected' : ''}`}
                 style={tab.width}
                 onClick={() => {
                   this.selectProfileTab(tab)
                 }}>
              {tab.name}</Col>
          ))}
        </Row>
        <div className="profile-operation">
          <Row type="flex" align="middle">
            <Col className="mode">
              <div>{this.state.mode}</div>
            </Col>
            <Col className="input-box">
              <Input type="search" placeholder="请输入" onChange={this.filterInputChange}/>
            </Col>
            <Col>
              <Button type="primary"
                      loading={this.state.saving}
                      onClick={() => {
                        this.saveFunctionProfile()
                      }}>保存
              </Button>
            </Col>
          </Row>
        </div>
        <div>
          {loading && (
            <div style={{
              'marginTop': '100px',
              'marginBottom': '50px',
              'marginLeft': 'auto',
              'marginRight': 'auto',
              'width': '20px'
            }}><Spin/></div>
          )}
        </div>
        <div>
          {
            !loading && (
              <div className="profile-content">
                <Row type="flex" className="profile-prompt" align="middle">
                  <Col span={8}>
                    <div className="profile-title">功能名称</div>
                  </Col>
                  <Col span={8}>
                    <div className="profile-value">值</div>
                  </Col>
                </Row>
                {functionProfileList.length > 0 ?
                  functionProfileList.map((profile, index) => (
                    (currentSelectTab === profile.type && this.filterProfile(profile.code, profile.description)) ?
                      (<Row type="flex" className="profile-item" key={profile.code} align="middle">
                        <Col span={8} className="profile-title">
                          <div className="profile-code">{profile.description}</div>
                          <div className="profile-description">
                            {this.renderOwner(profile)} {profile.code}
                          </div>
                        </Col>
                        <Col span={8} className="profile-value">
                          {this.renderProfileValue(profile)}
                        </Col>
                      </Row>) : null
                  )) : null}
              </div>
            )
          }
        </div>
      </div>
    )
  }
}

FunctionProfile.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    company: state.login.company,
  }
}

export default connect(mapStateToProps)(FunctionProfile)
